package info.nixbear.tgcms.admin.client.view;

import info.nixbear.tgcms.admin.client.activity.RedirectsActivity;
import info.nixbear.tgcms.admin.client.place.RedirectsPlace.RedirectEditPlace;
import info.nixbear.tgcms.admin.shared.request.RedirectProxy;

import java.util.List;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.web.bindery.requestfactory.shared.EntityProxyId;

public class RedirectsView extends Composite {

	private static RedirectsViewUiBinder uiBinder = GWT
			.create(RedirectsViewUiBinder.class);

	interface RedirectsViewUiBinder extends UiBinder<Widget, RedirectsView> {
	}

	RedirectsActivity redirectsActivity;
	
	public void setRedirectsActivity(RedirectsActivity redirectsActivity) {
		this.redirectsActivity = redirectsActivity;
	}

	ProvidesKey<RedirectProxy> keyProvider = new ProvidesKey<RedirectProxy>() {
		public EntityProxyId<RedirectProxy> getKey(RedirectProxy item) {
			return (item == null) ? null : item.stableId();
		}
	};

	@UiField(provided = true)
	final CellList<RedirectProxy> cellList = new CellList<RedirectProxy>(new RedirectCell(), keyProvider);//

	
	public RedirectsView() {
		initWidget(uiBinder.createAndBindUi(this));
		
		
		// Add a selection model using the same keyProvider.
		final SingleSelectionModel<RedirectProxy> selectionModel = 
			new SingleSelectionModel<RedirectProxy>(keyProvider);
		
		cellList.setSelectionModel(selectionModel);
		
		selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
			public void onSelectionChange(SelectionChangeEvent event) {
				RedirectProxy selected = selectionModel.getSelectedObject();
				if (selected != null) {
					redirectsActivity.goTo(new RedirectEditPlace(Long.toString(selected.getId()), selected));
					selectionModel.setSelected(selected, false);
				}
			}
		});

	}

	
	
	
	
	/**
	 * A custom {@link Cell} used to render a {@link Contact}.
	 */
	private static class RedirectCell extends AbstractCell<RedirectProxy> {
		@Override
		public void render(Context context, RedirectProxy redirect, SafeHtmlBuilder sb) {
			if (redirect != null) {
				sb.appendEscaped(redirect.getName()+": "+redirect.getFromUrl()+" > "+redirect.getToUrl());
			} else {
				sb.appendEscaped("null");
			}
		}
	}
	
	public void setRedirects(List<RedirectProxy> redirects) {
		cellList.setRowCount(redirects.size(), true);
		cellList.setRowData(0, redirects);
	}


	
}
